<template>
    <div>
        <input type="file" @change="handleFileChange" />
        <button @click="uploadFile">上传文件</button>
    </div>
    <div>
        <input v-model="fileName" placeholder="输入文件名" />
        <button @click="downloadFile">下载文件</button>
    </div>
</template>

<script lang="ts" setup name="FileUpload">
import { fileDownLoad, fileUpload } from '@/api/fileupload';
import { ref } from 'vue';

const selectedFile = ref(null);
const fileName = ref("");

const handleFileChange = (event: any) => {
    selectedFile.value = event.target.files[0];
};

const uploadFile = async () => {
    if (!selectedFile.value) {
        alert("请选择文件！");
        return;
    }

    const formData = new FormData();
    formData.append("file", selectedFile.value);

    try {
        const response = await fileUpload(formData);
        alert("文件上传成功！路径：" + response.data);
    } catch (error) {
        console.error("文件上传失败：", error);
        alert("上传失败，请检查日志！");
    }
};

const downloadFile = async () => {
    if (!fileName.value) {
        alert("请输入文件名！");
        return;
    }

    try {
        const response = await fileDownLoad({ fileName: fileName.value });
        console.log("response:", response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", fileName.value);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    } catch (error) {
        console.error("文件下载失败：", error);
        alert("下载失败，请检查日志！");
    }
};

</script>

<style lang="scss" scoped></style>